<?php

namespace app\supplier\controller\product;

use app\common\model\file\UploadFile;
use app\common\model\product\Brand;
use app\common\model\product\Car;
use app\common\model\settings\Setting;
use app\common\model\user\Grade;
use app\supplier\model\product\Product as ProductModel;
use app\common\model\product\Category as CategoryModel;
use app\supplier\service\ProductService;
use app\supplier\model\supplier\Supplier as SupplierModel;
use app\supplier\controller\Controller;

/**
 * 商品管理控制器
 */
class Product extends Controller
{
    /**
     * 商品列表(全部)
     */
    public function index()
    {
        $supplier = SupplierModel::detail($this->getSupplierId());
        // 获取全部商品列表
        $model = new ProductModel;
        $list = $model->getList(array_merge(['status' => -1, 'shop_supplier_id' => $this->getSupplierId()], $this->postData()));
        // 商品分类
        $category = CategoryModel::getCacheTree();
        // 数量
        $product_count = [
            'sell' => $model->getCount('sell', $this->getSupplierId()),
            'stock' => $model->getCount('stock', $this->getSupplierId()),
            'recovery' => $model->getCount('recovery', $this->getSupplierId()),
            'draft' => $model->getCount('draft', $this->getSupplierId()),
            'lower' => $model->getCount('lower', $this->getSupplierId()),
            'audit' => $model->getCount('audit', $this->getSupplierId()),
            'no_audit' => $model->getCount('no_audit', $this->getSupplierId())
        ];
        return $this->renderSuccess('', compact('list', 'category', 'supplier', 'product_count'));
    }

    /**
     * 添加商品
     */
    public function add($scene = 'add')
    {
        // get请求
        if ($this->request->isGet()) {
            return $this->getBaseData();
        }
        //post请求
        $data = json_decode($this->postData()['params'], true);
        if ($scene == 'copy') {
            unset($data['create_time']);
            unset($data['sku']['product_sku_id']);
            unset($data['sku']['product_id']);
            unset($data['product_sku']['product_sku_id']);
            unset($data['product_sku']['product_id']);
            // 如果是多规格
            if ($data['spec_type'] == 20) {
                foreach ($data['spec_many']['spec_list'] as &$sku) {
                    $sku['product_sku_id'] = 0;
                }
            }
            //初始化销量等数据
            $data['sales_initial'] = 0;
        }
        //是否需要审核
        $add_audit = Setting::getItem('store')['add_audit'];
        if ($add_audit == 0) {
            // 如果不需要审核，则审核状态是已审核
            $data['audit_status'] = 10;
        }
        $model = new ProductModel;
        if (isset($data['product_id'])) {
            unset($data['product_id']);
        }
        $data['shop_supplier_id'] = $this->getSupplierId();
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 获取基础数据
     */
    public function getBaseData()
    {
        return $this->renderSuccess('', array_merge(ProductService::getEditData(null, 'add', $this->getSupplierId()), []));
    }

    /**
     * 获取编辑数据
     */
    public function getEditData($product_id, $scene = 'edit')
    {
        $model = ProductModel::detail($product_id);
        return $this->renderSuccess('', array_merge(ProductService::getEditData($model, $scene, $this->getSupplierId()), compact('model')));
    }

    /**
     * 商品编辑
     */
    public function edit($product_id, $scene = 'edit')
    {
        if ($this->request->isGet()) {
            $model = ProductModel::detail($product_id);
            if($model->car_ids){
                $model->car_ids = explode(',', $model->car_ids);
                $model->car_remark = $model->car_remark?json_decode($model->car_remark,true):[];
                $model->car_list = Car::whereIn('id',$model->car_ids)->order('brand,serie,models DESC')->select();
            }else{
                $model->car_ids = [];
                $model->car_list = [];
                $model->car_remark = [];
            }
            return $this->renderSuccess('', array_merge(ProductService::getEditData($model, $scene, $this->getSupplierId()), compact('model')));
        }
        if ($scene == 'copy') {
            return $this->add($scene);
        }
        // 商品详情
        $model = ProductModel::detail($product_id);
        // 更新记录
        if ($model->edit(json_decode($this->postData()['params'], true), $this->getSupplierId())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 修改商品状态
     */
    public function state($product_id, $state)
    {
        // 商品详情
        $model = ProductModel::detail($product_id);
        if ($model['audit_status'] != 10) {
            return $this->renderError('商品状态不正确');
        }
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商品
     */
    public function delete($product_id)
    {
        // 商品详情
        $model = ProductModel::detail($product_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    public function getCarData()
    {
        $data = $this->getData();
        $id = $data['id'] ?? null;
        $chassis_code = $data['chassis_code'] ?? null;
        $search_data = $data['search_data'] ?? false;
        $search_car = $data['search_car'] ?? false;
        //$search_data=false时获取初始化数据，否则表示获取车辆数据
    
        if($search_data){
            $where = [];
            $where['depth'] = 4;
            if(isset($id[0])){
                $where[] = ['brand', '=', $id[0]];
            }
            if(isset($id[1])){
                $where[] = ['manufacturers', '=', $id[1]];
            }
            if(isset($id[2])){
                $where[] = ['serie', '=', $id[2]];
            }
            if(isset($id[3])){
                $where[] = ['chassis_code', '=', $id[3]];
            }
            if(isset($id[4])){
                $where[] = ['models', '=', $id[4]];
            }
            if($chassis_code){
                $where[] = ['chassis_code|models', 'like', '%' . $chassis_code . '%'];
            }
            // 获取所有数据
            $cars = Car::where($where)->order('models ASC')->select();
            return $this->renderSuccess('', $cars);
        }else{
            // 获取所有数据，优先从缓存
            $cacheKey = 'car_group_tree';
            $data = cache($cacheKey);
            if (!$data) {
                $cars = Car::field('id,name,brand,manufacturers,serie,models,chassis_code')->select()->toArray();

                // 分组构建递归方法
                function groupByFields($data, $fields) {
                    if (empty($fields)) {
                        return [];
                    }
                    $field = array_shift($fields);
                    $grouped = [];
                    foreach ($data as $item) {
                        $key = $item[$field] ?? '';
                        if (!$key) continue;
                        if (!isset($grouped[$key])) {
                            $grouped[$key] = [
                                'value' => $key,
                                'label' => $key,
                                'children' => []
                            ];
                        }
                        $grouped[$key]['children'][] = $item;
                    }
                    foreach ($grouped as &$group) {
                        $group['children'] = groupByFields($group['children'], $fields);
                        if (empty($group['children'])) {
                            $group['children'] = array_map(function($car) {
                                return [
                                    'value' => $car['id'],
                                    'label' => $car['models'] ?: $car['name']
                                ];
                            }, $group['children']);
                        }
                    }
                    return array_values($grouped);
                }
                $fields = ['brand', 'manufacturers', 'serie', 'chassis_code', 'models'];
                $data = groupByFields($cars, $fields);
                // 缓存1小时
                cache($cacheKey, $data, 3600);
            }
            return $this->renderSuccess('', $data);

        }

    }
   /**
     * 获取车型数据
     */
    public function getCarDatas(){
        $data = $this->getData();
        $id = $data['id'] ?? null;
        $chassis_code = $data['chassis_code'] ?? null;
        $search_data = $data['search_data'] ?? false;

        if ($id || $chassis_code) {
            if($search_data == 'true' || $search_data === true){
                // 搜索模式：循环获取到最后一级 depth=4 的车型数据
                $searchValue = $data['search_value'] ?? '';
                
                // 添加调试信息
                $currentCar = Car::where('id', $id)->find();
                $debugInfo = [
                    'input_id' => $id,
                    'search_value' => $searchValue,
                    'current_car' => $currentCar ? $currentCar->toArray() : null,
                ];
                $result = $this->searchCarToDepth4($id,$chassis_code, $searchValue);
                
                // 如果没有结果，返回调试信息
                if (empty($result)) {
                    return $this->renderSuccess('', [
                        'debug' => $debugInfo,
                        'result' => $result,
                        'children_count' => Car::where('parentid', $id)->count()
                    ]);
                }
                
            }else{
                // 根据传入的id获取parentid=id的数据
                $result = Car::where('parentid', $id)->select();
            }
        } else {
            // 默认获取depth=1的数据
            $result = Car::where('depth', 1)->select();
        }
        
        return $this->renderSuccess('', $result);
    }

    /**
     * 搜索车型数据，循环到depth=4
     */
    private function searchCarToDepth4($parentId,$chassis_code, $searchValue = '')
    {
        if($chassis_code && !$parentId){
            // 获取当前节点信息
            $finalResults = Car::where('depth', 4)->where('name|chassis_code', 'like', '%' . $chassis_code . '%')->select();
        }else{
            // 获取当前节点信息
            $currentCar = Car::where('id', $parentId)->find();
            if (!$currentCar) {
                return [];
            }
            // 如果当前已经是depth=4，直接返回当前级别的兄弟节点
            if ($currentCar->depth == 4) {
                $query = Car::where('parentid', $currentCar->parentid);
                if (!empty($searchValue)) {
                    $query->where('name', 'like', '%' . $searchValue . '%');
                }
                if($chassis_code){
                    $query->where('chassis_code', 'like', '%' . $chassis_code . '%');
                }
                return $query->select()->toArray();
            }

            // 递归搜索所有子级，直到找到depth=4的数据
            $finalResults = [];
            $this->searchRecursive($parentId,$chassis_code, $searchValue, $finalResults);
        }
        return $finalResults;
    }

    /**
     * 递归搜索方法
     */
    private function searchRecursive($parentId,$chassis_code, $searchValue, &$results)
    {
        // 获取当前级别的所有子项
        $children = Car::where(['parentid'=> $parentId])->select();
        foreach ($children as $child) {
            if ($child->depth == 4) {
                if($chassis_code && (stripos($child->chassis_code, $chassis_code) === false  && stripos($child->name, $chassis_code) === false)){
                    continue;
                }
                // 如果到达最终级别
                if (empty($searchValue) || stripos($child->name, $searchValue) !== false) {
                    $results[] = $child->toArray();
                }
            } else {
                // 如果还没到最终级别，继续递归搜索
                $this->searchRecursive($child->id,$chassis_code, $searchValue, $results);
            }
        }
    }

    /**
     * 批量添加
     *
     */
    public function batchAdd()
    {
        // // get请求
        // if ($this->request->isGet()) {
        //     return $this->getBaseData();
        // }
        // //post请求
        // $data = json_decode($this->postData()['params'], true);
        // halt($data);

        // get请求
        if ($this->request->isGet()) {
            return $this->getBaseData();
        }
        //post请求
        $data = json_decode($this->postData()['params'], true);
        $app_id = request()->header('appId');
        //是否需要审核
        $add_audit = Setting::getItem('store')['add_audit'];
        if ($add_audit == 0) {
            // 如果不需要审核，则审核状态是已审核
            $data['audit_status'] = 10;
        }
        $model = new ProductModel;
        if (isset($data['product_id'])) {
            unset($data['product_id']);
        }
        $data['shop_supplier_id'] = $this->getSupplierId();
        $file = UploadFile::where(['is_delete' => 0,'app_id' => $app_id])
        ->where('real_name','like',$data['product_no'].'.%')
        ->order('real_name ASC')
        ->column('file_id,save_name as file_path');
        if($file){
            $data['image'] = $file;
        }else{
            $data['image'] = [
                [
                    'file_id' =>'3390',
                    'file_path' =>'20251017/a3a37f0d975ec3440c04ec4bb78c22fd.png',
                ]
            ];
        }
        //设置会员价格
        if($data['is_enable_grade'] == 1 && $data['is_alone_grade'] == 1){
            $data['alone_grade_equity'] = [];
            $grade_id = Grade::where(['is_delete' => 0,'app_id' => $app_id])->order('weight ASC')->column('grade_id');
            foreach ($grade_id as $k=>$v){
                $k++;
                $data['alone_grade_equity'][$v] = (string)$data['lv'.$k];
            }
        }
        //设置品牌
        if(isset($data['brand_name']) && !empty($data['brand_name'])){
            $brand_id = Brand::where('name',$data['brand_name'])->value('id');
            $data['brand_id'] = $brand_id??0;
        }
        $data['sku']['product_no'] = $data['product_no'];
        $data['sku']['stock_num'] = $data['product_stock'];
        $data['sku']['product_price'] = $data['product_price'];
        $data['sku']['line_price'] = $data['line_price'];
        $data['logistics'] = explode(',', $data['logistics']);
        $product = $model->where(['product_no'=>$data['product_no'],'is_delete' => 0,'app_id' => $app_id])->find();
        if($product){
            $model = ProductModel::detail($product->product_id);
            $data = array_merge($model->toArray(),$data);
            if ($model->edit($data, $data['shop_supplier_id'])) {
                return $this->renderSuccess('操作成功');
            }
        }else{
            if ($model->add($data)) {
                return $this->renderSuccess('操作成功');
            }
        }

        return $this->renderError($model->getError() ?: '添加失败');
    }

}
